<?php

/**
 *   OPENSHOP 管理中心条形码管理
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: barcode.php,v 1.0 2009/06/17 08:36:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');
$exc = new exchange($os->table("goods_barcode"), $db, 'barcode_id', 'barcode');

/*------------------------------------------------------ */
//-- 条形码生成
/*------------------------------------------------------ */
if($_REQUEST['act'] == 'generate'){
	//检查权限
	admin_priv();
		
    $smarty->assign('ur_here',      '商品条形码生成');
    $smarty->assign('action_link',  array('text' => '商品条形码维护管理', 'href' => 'barcode.php?act=manage'));
    $smarty->assign('cat_list',     cat_list());
    $smarty->assign('brand_list',   get_brand_list());
    $smarty->assign('generate_scheme_list',   get_generate_scheme_list());
    $smarty->assign('form_act',   'create_barcode');
    
    assign_query_info();
    
    $smarty->display('barcode_info.tpl');	
    
}elseif($_REQUEST['act'] == 'get_goods_list'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_goods_list($filters);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] = array('value' => $val['goods_id'],
                       'text'  => $val['goods_name'] . ' -- [' . $val['goods_sn'] . ']',
                       'data'  => $val['shop_price']);
    }

    make_json_result($opt);
}elseif($_REQUEST['act']=='add_goods'){
	check_authz_json('generate_barcode');
		
    include_once(ROOT_PATH . 'includes/cls_json.php');
    
    $json = new JSON;
    $fittings   = $json->decode($_GET['add_ids']);	
    $arr = $db->getAll("SELECT goods_id,goods_name,goods_sn FROM " . $os->table('goods') . " WHERE " . db_create_in($fittings, 'goods_id') . 
                       " ORDER BY goods_id DESC");
    
    $opt = array();

    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['goods_id'],
                       'text'  => $val['goods_name'] . ' -- [' . $val['goods_sn'] . ']',
                       'data'       => '');
    }

    clear_cache_files();
    make_json_result($opt);	
}elseif($_REQUEST['act']=='create_barcode'){
	if(empty($_POST['goods_ids'])){
		sys_msg('生成条形码商品必须选择');	exit();	
	}
	$goods_ids = explode(',', $_POST['goods_ids']);
    if(!is_array($goods_ids)){
    	sys_msg('生成条形码商品必须选择');	exit();	
    }
    if(empty($_POST['generate_scheme'])){
    	sys_msg('条形码生成方案必须选择');	exit();	
    }
    $scheme_id = intval($_POST['generate_scheme']);
    $is_cover = !empty($_POST['is_cover']) ? intval($_POST['is_cover']) : 0;
    goods_barcode_generator($goods_ids, $scheme_id, $is_cover);
    
    /* 记日志 */
    admin_log($_POST['goods_ids'], 'add', 'barcode');

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    $links = array(
        array('href' => 'barcode.php?act=generate', 'text' => '继续生成新的商品条形码'),
        array('href' => 'barcode.php?act=manage', 'text' => '返回商品条形码维护')
    );
    sys_msg('添加商品条形码成功', 0, $links);  
}elseif($_REQUEST['act']=='manage'){
    /* 检查权限 */
    admin_priv();  
  
    $smarty->assign('ur_here',      '商品条形码维护');    
	$smarty->assign('action_link',  array('text' => '商品条形码生成', 'href' => 'barcode.php?act=generate'));    
    $smarty->assign('full_page',    1);
		
    $smarty->assign('cat_list',     cat_list(0, $cat_id));
    $smarty->assign('brand_list',   get_brand_list());

    $goods_barcode_list = get_goods_barcode_list();

    $smarty->assign('goods_barcode_list',  $goods_barcode_list['barcode']);
    $smarty->assign('filter',       $goods_barcode_list['filter']);
    $smarty->assign('record_count', $goods_barcode_list['record_count']);
    $smarty->assign('page_count',   $goods_barcode_list['page_count']);
    
    assign_query_info();
    
    $smarty->display('barcode_list.tpl');	
}elseif($_REQUEST['act']=='query_barcode'){	
    $list = get_goods_barcode_list();
    $smarty->assign('goods_barcode_list',           $list['barcode']);
    $smarty->assign('filter',         		$list['filter']);
    $smarty->assign('record_count',   		$list['record_count']);
    $smarty->assign('page_count',     		$list['page_count']);
    
    make_json_result($smarty->fetch('barcode_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  
}elseif($_REQUEST['act']=='edit_barcode'){
    check_authz_json('edit_barcode');

    $id     = intval($_POST['id']);
    $name   = json_str_iconv(trim($_POST['val']));

    /* 检查名称是否重复 */
    if (!$exc->is_only("barcode", $name, $id))
    {    	
        make_json_error(sprintf('商品条形码 %s 已经存在！', $name));
    }
    else
    {
        if ($exc->edit("barcode = '$name'", $id))
        {
            admin_log($name, 'edit', 'barcode');
            clear_cache_files();
            make_json_result(stripslashes($name));
        }
        else
        {
            make_json_result(sprintf('商品条形码 %s 修改失败！', $name));
        }
    }	
}elseif($_REQUEST['act']=='remove_barcode'){	
    check_authz_json('drop_barcode');

    $barcode_id = intval($_GET['id']);
    $barcode = $db->getOne("SELECT barcode FROM " . $os->table('goods_barcode') . " WHERE barcode_id='$barcode_id'");    
    if($db->query("DELETE FROM " . $os->table('goods_barcode') . " WHERE barcode_id='$barcode_id'")){
	    /* 记日志 */
	    admin_log($barcode, 'remove', 'barcode');	
    }

    /* 清除缓存 */
    clear_cache_files();

    $url = 'barcode.php?act=query_barcode&' . str_replace('act=remove_barcode', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;	
}elseif($_REQUEST['act']=='batch_barcode'){
    /* 检查权限 */
    admin_priv('drop_barcode');
    
    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']))
    {
        sys_msg('没有选择记录！');
    }
    else
    {
        $ids = $_POST['checkboxes'];

        if (isset($_POST['remove']))
        {
            /* 删除记录 */
            $sql = "DELETE FROM " . $os->table('goods_barcode') .
                    " WHERE barcode_id " . db_create_in($ids);
            $db->query($sql);

            /* 记日志 */
            admin_log('', 'batch_remove', 'barcode');

            /* 清除缓存 */
            clear_cache_files();

            sys_msg('批量删除商品条形码成功！');
        }
    }	
}

elseif($_REQUEST['act']=='list_goods'){
    /* 检查权限 */
    admin_priv();  
    	
    $smarty->assign('ur_here',       '商品条码打印');
    $smarty->assign('full_page',     1);
 	$smarty->assign('form_action',   'add_print_code_goods');    
    $smarty->assign('cat_list',      cat_list(0, $cat_id));
    $smarty->assign('brand_list',    get_brand_list());
      
    $smarty->assign('generate_scheme_list',   get_generate_scheme_list());
    
    $list = get_print_code_goods_list();  
    $smarty->assign('supplier_goods_list', $list['items']);    
    $smarty->assign('filter',              $list['filter']);
    $smarty->assign('page_count',          $list['page_count']); 
    $smarty->assign('record_count',        $list['record_count']);
    
    assign_query_info();
    $smarty->display('goods_print_barcode_list.tpl');	
}

elseif ($_REQUEST['act']=='query_goods'){

	$list = get_print_code_goods_list();
    $smarty->assign('supplier_goods_list',  $list['items']);
    $smarty->assign('filter',               $list['filter']);
    $smarty->assign('record_count',         $list['record_count']);
    $smarty->assign('page_count',           $list['page_count']);
    
    make_json_result($smarty->fetch('goods_print_barcode_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  
}

elseif($_REQUEST['act']=='add_print_code_goods'){
	
	if(empty($_POST['goods_nums'])){
		sys_msg('生成唯一码商品必须选择');	exit();	
	}
		
    if(empty($_POST['generate_scheme'])){
    	sys_msg('条形码生成方案必须选择');	exit();	
    }
    $scheme_id = intval($_POST['generate_scheme']);
    if(!empty($_SESSION['code_ids'])){
    	unset($_SESSION['code_ids']);
    }
	goods_barcode_generator2($_POST['goods_nums'], $scheme_id);

	    /* 记日志 */
    admin_log($_POST['goods_nums'], 'add', 'unique_code');

    /* 清除缓存 */
    clear_cache_files();

    $url = 'barcode.php?act=print_goods_code';

    os_header("Location: $url\n");
    exit;
}

elseif($_REQUEST['act']=='print_goods_code'){
	if(empty($_SESSION['code_ids'])){
        sys_msg('生成打印唯一码失败！');
        exit();		
	}
	$ids = $_SESSION['code_ids'];
	$unique_codes = get_unique_codes($ids);

	update_unique_code_printlog($unique_codes);

	//start test data 
	//print_r($unique_codes); 
	//end test data 
	//获取模板文件
	$template_desc = $db->getOne("SELECT template_desc FROM " . $os->table('barcode_template') . " LIMIT 1");
	
	$script = "";
	$print_script = "";
	$i=0;
	foreach ($unique_codes as $uc) {
		
		$smarty->assign('uc',$uc);
		$script = $script.' function SetPrintPage'.$i.'(){';
		$script = $script.$smarty->fetch("str:$template_desc");
		$script = $script.'}';
		$script = $script.'
		';
		$i++;
	}
	$smarty->assign('num',$i);
	$smarty->assign('unique_codes',$unique_codes);
	$smarty->assign('script',$script);
	$smarty->assign('print_script',$print_script);
    
    assign_query_info();
    $smarty->display('print_goods_code.tpl');
}

elseif($_REQUEST['act']=='edit_print_template'){
	/* 检查权限 */
    admin_priv();

    $smarty->assign('ur_here',      '商品条码打印模板');

	$template_desc = $db->getOne("SELECT template_desc FROM " . $os->table('barcode_template') . " LIMIT 1");
	$smarty->assign('template_desc', $template_desc);
	
    assign_query_info();
    $smarty->display('goods_code_print_template.tpl');
}

elseif($_REQUEST['act']=='do_edit_print_template'){

	if(empty($_POST['template_desc'])){
        sys_msg('打印模板内容不能为空！');
        exit();
	}
	$barcode_tpl_id = $db->getOne("SELECT barcode_tpl_id FROM " . $os->table('barcode_template') . " WHERE barcode_tpl_id=1");	
	$tpl_desc = strval(trim($_POST['template_desc']));
	if(!empty($barcode_tpl_id) && $barcode_tpl_id>0){
		$sql = "UPDATE " . $os->table('barcode_template') . " SET template_desc='$tpl_desc' WHERE barcode_tpl_id=1";
	}else{
		$sql = "INSERT INTO " . $os->table('barcode_template') . "(barcode_tpl_id,template_desc) VALUES(1,'$tpl_desc')";
	}
	$db->query($sql);
	
    /* 记日志 */
    admin_log('', 'edit', 'barcode_print_template');

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    $links = array(
        array('href' => 'barcode.php?act=edit_print_template', 'text' => '继续编辑商品条码打印模板'),
        array('href' => 'barcode.php?act=list_goods', 'text' => '商品条码打印')
    );
    sys_msg('编辑商品条码打印模板成功', 0, $links); 	
}

function update_unique_code_printlog($unique_codes){
	if(!is_array($unique_codes)){
		return false;
	}
	foreach ($unique_codes as $c){
	    $sql = 'INSERT INTO ' . $GLOBALS['os']->table('unique_code_printlog') . ' (log_time, user_id, unique_code, ip_address) ' .
	            " VALUES ('" . gmtime() . "', $_SESSION[admin_id], '" . $c['unique_code'] . "', '" . real_ip() . "')";
	    $GLOBALS['db']->query($sql);
	}	
}

function get_unique_codes($ids){
	$uc_sql  = "SELECT uc.color_id,uc.size_id,uc.barcode,uc.old_code,uc.code,g.goods_sn,c.cat_code FROM " . $GLOBALS['os']->table('goods_unique_code') . 
	           " uc LEFT JOIN " . $GLOBALS['os']->table('goods') . " g ON uc.goods_id=g.goods_id LEFT JOIN " .
	           $GLOBALS['os']->table('category') . " c ON g.cat_id=c.cat_id WHERE " . db_create_in($ids, 'uc.code_id');
	$uc_res  = $GLOBALS['db']->query($uc_sql);
	$arr = array();
	$arr_colors = array();
	$arr_sizes = array();
	while ($uc_row = $GLOBALS['db']->fetchRow($uc_res)) {
		$prefix = '';
		for($code=$uc_row['code'];$code>$uc_row['old_code'];$code--){
			$code_len = strlen($code);
			if($code_len<4){
				$arr_zero = array_fill(0, (4-$code_len), 0);
				$prefix = implode('', $arr_zero);
			}	
			$uc_row['unique_code'] = $uc_row['barcode'] . $prefix . $code;	
			$arr[] = $uc_row;	
		}
		$arr_colors[] = $uc_row['color_id'];
		$arr_sizes[]  = $uc_row['size_id'];
	}
	$arr_colors = array_unique($arr_colors);
	$arr_sizes = array_unique($arr_sizes);
	$c_sql  = "SELECT color_id, color_code, color_name FROM " . $GLOBALS['os']->table('color') . " WHERE " . db_create_in($arr_colors, 'color_id');
	$c_res = $GLOBALS['db']->query($c_sql);
	while ($c_row = $GLOBALS['db']->fetchRow($c_res)){
		$colors[$c_row['color_id']]['color_id']   = $c_row['color_id'];
		$colors[$c_row['color_id']]['color_code'] = $c_row['color_code'];
		$colors[$c_row['color_id']]['color_name'] = $c_row['color_name'];
	}
	
	$s_sql  = "SELECT size_id, size_code, size_name FROM " . $GLOBALS['os']->table('size') . " WHERE " . db_create_in($arr_sizes, 'size_id');
	$s_res = $GLOBALS['db']->query($s_sql);
	while ($s_row = $GLOBALS['db']->fetchRow($s_res)){
		$sizes[$s_row['size_id']]['size_id']   = $s_row['size_id'];
		$sizes[$s_row['size_id']]['size_code'] = $s_row['size_code'];
		$sizes[$s_row['size_id']]['size_name'] = $s_row['size_name'];		
	}
	$arr_uc = array();
	foreach ($arr as $uc){
		if(!empty($colors[$uc['color_id']])){
			$uc['color_code'] = $colors[$uc['color_id']]['color_code'];
			$uc['color_name'] = $colors[$uc['color_id']]['color_name'];
		}
		if(!empty($sizes[$uc['size_id']])){
			$uc['size_code'] = $sizes[$uc['size_id']]['size_code'];
			$uc['size_name'] = $sizes[$uc['size_id']]['size_name'];
		}		
		$arr_uc[] = $uc;
	}
	return $arr_uc;
}

function goods_barcode_generator2($haystack=array(), $scheme_id){
	$goods_colors = array();
	$goods_sizes  = array();
	$goods_list   = array();
	
	$arr_goods = array_keys($haystack);
		
	$g_sql  = "SELECT g.goods_id,g.goods_sn,c.cat_id,c.cat_code FROM " . $GLOBALS['os']->table('goods') . " g LEFT JOIN " . 
	          $GLOBALS['os']->table('category') . " c ON g.cat_id=c.cat_id WHERE g.is_delete=0 AND g.is_real=1 AND " . 
	          db_create_in($arr_goods, 'g.goods_id');
	$g_res  = $GLOBALS['db']->query($g_sql);    
	while ($g_row = $GLOBALS['db']->fetchRow($g_res)) {
		$goods_list[$g_row['goods_id']] =  $g_row;
	}
	
	$c_sql  = "SELECT gc.goods_id, c.color_id, c.color_code FROM " . $GLOBALS['os']->table('goods_color') . " gc JOIN " . 
	        $GLOBALS['os']->table('color') . " c ON gc.color_id=c.color_id WHERE " . db_create_in(array_keys($goods_list), 'gc.goods_id');
	$c_res = $GLOBALS['db']->query($c_sql);
	while ($c_row = $GLOBALS['db']->fetchRow($c_res)){
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_id']   = $c_row['color_id'];
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_code'] = $c_row['color_code'];
	}
	
	$s_sql  = "SELECT gs.goods_id, s.size_id, s.size_code FROM " . $GLOBALS['os']->table('goods_size') . " gs JOIN " . 
	        $GLOBALS['os']->table('size') . " s ON gs.size_id=s.size_id WHERE " . db_create_in(array_keys($goods_list), 'gs.goods_id');
	$s_res = $GLOBALS['db']->query($s_sql);
	while ($s_row = $GLOBALS['db']->fetchRow($s_res)){
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_id']   = $s_row['size_id'];
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_code'] = $s_row['size_code'];
	}
	
	$sql = "SELECT * FROM " . $GLOBALS['os']->table('barcode_generate_scheme') . " WHERE scheme_id=" . intval($scheme_id);
    $generate_scheme = $GLOBALS['db']->getRow($sql);
    foreach($goods_list as $goods_id=>$g){
    	if(!empty($haystack[$goods_id])){
    		foreach ($haystack[$goods_id] as $color_id=>$arr_sizes){
    			if(!empty($goods_colors[$goods_id][$color_id])){
    				foreach ($arr_sizes as $size_id=>$num){
    					if(!empty($goods_sizes[$goods_id][$size_id]) && (is_numeric($num) && $num>0)){
    						$color_code = $goods_colors[$goods_id][$color_id]['color_code'];
    						$size_code  = $goods_sizes[$goods_id][$size_id]['size_code'];   
													
		    				$barcode  = barcode_generator($generate_scheme, $g['cat_code'], $g['goods_sn'], $color_code, $size_code);
							$check_uc = $GLOBALS['db']->getRow("SELECT code_id,code FROM " . $GLOBALS['os']->table('goods_unique_code') . 
							  			" WHERE goods_id='$goods_id' AND color_id='$color_id' AND size_id='$size_id' AND barcode='$barcode'");
							$code = $check_uc['code']+$num;
							if($check_uc['code_id']>0 && $code<=9999){
								$sql_ext = " ON DUPLICATE KEY UPDATE old_code=code,code='$code'";
							}elseif($check_uc['code_id']>0 && $code>9999){
    					        $sql_ext = " ON DUPLICATE KEY UPDATE old_code=old_code,code=code";
    				        }	
								    				
		    				$sql = "INSERT INTO " . $GLOBALS['os']->table('goods_unique_code') . "(goods_id, color_id, size_id, barcode," . 
		    				       " old_code, code) VALUES ('$goods_id', '$color_id', '$size_id', '$barcode', 0, $num) " . $sql_ext;
		    				       
		    				$GLOBALS['db']->query($sql);
		    				$code_id = $GLOBALS['db']->getOne("SELECT code_id FROM " . $GLOBALS['os']->table('goods_unique_code') . " WHERE barcode='$barcode'");
		    				$_SESSION['code_ids'][] = $code_id;
    					}
	    			}
    			}
    		}
    	}
    }
}

function get_print_code_goods_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'goods_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['cat_id']           = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        $filter['brand_id']         = empty($_REQUEST['brand_id']) ? 0 : intval($_REQUEST['brand_id']);
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        
        $ext_sql = " WHERE g.is_delete=0 AND g.is_real=1";
		$ext_sql .= $filter['cat_id'] > 0 ? " AND " . get_children($filter['cat_id']) : '';
		
        /* 品牌 */
        if ($filter['brand_id'])
        {
            $ext_sql .= " AND g.brand_id='$filter[brand_id]'";
        }   

        /* 关键字 */
        if (!empty($filter['keyword']))
        { 
			$filter['keyword'] = urldecode($filter['keyword']);
            $ext_sql .= " AND (g.goods_sn LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR g.goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }	

        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('goods') . " g " . $ext_sql;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT g.goods_id,g.goods_name,g.goods_sn FROM " . $GLOBALS['os']->table('goods') . 
               " g " . $ext_sql . " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $goods_list   = array();
	$goods_colors = array();
	$goods_sizes  = array();
	
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $goods_list[$row['goods_id']] = $row;
    }
    
	$c_sql  = "SELECT gc.goods_id, c.color_id, c.color_code, c.color_name FROM " . $GLOBALS['os']->table('goods_color') . " gc JOIN " . 
	        $GLOBALS['os']->table('color') . " c ON gc.color_id=c.color_id WHERE " . db_create_in(array_keys($goods_list), 'gc.goods_id');
	$c_res = $GLOBALS['db']->query($c_sql);
	while ($c_row = $GLOBALS['db']->fetchRow($c_res)){
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_id']   = $c_row['color_id'];
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_code'] = $c_row['color_code'];
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_name'] = $c_row['color_name'];
	}
	
	$s_sql  = "SELECT gs.goods_id, s.size_id, s.size_code, s.size_name FROM " . $GLOBALS['os']->table('goods_size') . " gs JOIN " . 
	        $GLOBALS['os']->table('size') . " s ON gs.size_id=s.size_id WHERE " . db_create_in(array_keys($goods_list), 'gs.goods_id');
	$s_res = $GLOBALS['db']->query($s_sql);
	while ($s_row = $GLOBALS['db']->fetchRow($s_res)){
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_id']   = $s_row['size_id'];
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_code'] = $s_row['size_code'];
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_name'] = $s_row['size_name'];		
	}
    $goods_specs = array();
    foreach($goods_list as $goods_id=>$g){
    	if(!empty($goods_colors[$goods_id]) && !empty($goods_sizes[$goods_id])){
    		foreach ($goods_colors[$goods_id] as $color_id=>$gc){
    			$goods_specs[$goods_id][$color_id] = $gc;
    			foreach($goods_sizes[$goods_id] as $size_id=>$gs){ 
                       $goods_specs[$goods_id][$color_id]['size_specs'][$size_id] = $gs;
    			}
    		}
    	}
    }
    $arr = array();
    foreach($goods_list as $g){
    	$g['specs'] = !empty($goods_specs[$g['goods_id']]) ? $goods_specs[$g['goods_id']] : 0;
    	$g['short_goods_name']  = sub_str($g['goods_name'], 20);
    	$arr[] = $g;
    }
    return array('items' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

function get_goods_barcode_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'g.goods_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['cat_id']           = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        $filter['brand_id']         = empty($_REQUEST['brand_id']) ? 0 : intval($_REQUEST['brand_id']);
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        
		$where = $filter['cat_id'] > 0 ? " AND " . get_children($filter['cat_id']) : '';
		
        /* 品牌 */
        if ($filter['brand_id'])
        {
            $where .= " AND g.brand_id='$filter[brand_id]'";
        }   

        /* 关键字 */
        if (!empty($filter['keyword']))
        { 
			$filter['keyword'] = urldecode($filter['keyword']);
            $where .= " AND (g.goods_sn LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR g.goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }
            
        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('goods_barcode') . " gb LEFT JOIN " . $GLOBALS['os']->table('goods') . 
               " g ON gb.goods_id=g.goods_id LEFT JOIN " . $GLOBALS['os']->table('color') . " c ON gb.color_id=c.color_id LEFT JOIN " . 
               $GLOBALS['os']->table('size') . " s ON gb.size_id=s.size_id WHERE g.is_delete=0 AND g.is_real=1 " . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT gb.barcode_id,gb.barcode,g.goods_id,g.goods_name,g.goods_sn,gb.barcode,c.color_name,c.color_code," . 
               "s.size_name,s.size_code FROM " . $GLOBALS['os']->table('goods_barcode') . " gb LEFT JOIN " . 
               $GLOBALS['os']->table('goods') . " g ON gb.goods_id=g.goods_id LEFT JOIN " . $GLOBALS['os']->table('color') . 
               " c ON gb.color_id=c.color_id " . " LEFT JOIN " . $GLOBALS['os']->table('size') . " s ON gb.size_id=s.size_id WHERE " . 
               " g.is_delete=0 AND g.is_real=1 " . $where . " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
    	$arr[] = $row;
    }
    return array('barcode' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function goods_barcode_generator($arr_goods, $scheme_id, $is_cover=0){
	$goods_colors = array();
	$goods_sizes  = array();
	$goods_list   = array();
	
	$g_sql  = "SELECT g.goods_id,g.goods_sn,c.cat_id,c.cat_code FROM " . $GLOBALS['os']->table('goods') . " g LEFT JOIN " . 
	          $GLOBALS['os']->table('category') . " c ON g.cat_id=c.cat_id WHERE g.is_delete=0 AND g.is_real=1 AND " . 
	          db_create_in($arr_goods, 'g.goods_id');
	$g_res  = $GLOBALS['db']->query($g_sql);    
	while ($g_row = $GLOBALS['db']->fetchRow($g_res)) {
		$goods_list[$g_row['goods_id']] =  $g_row;
	}
	
	$c_sql  = "SELECT gc.goods_id, c.color_id, c.color_code FROM " . $GLOBALS['os']->table('goods_color') . " gc JOIN " . 
	        $GLOBALS['os']->table('color') . " c ON gc.color_id=c.color_id WHERE " . db_create_in(array_keys($goods_list), 'gc.goods_id');
	$c_res = $GLOBALS['db']->query($c_sql);
	while ($c_row = $GLOBALS['db']->fetchRow($c_res)){
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_id']   = $c_row['color_id'];
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_code'] = $c_row['color_code'];
	}
	
	$s_sql  = "SELECT gs.goods_id, s.size_id, s.size_code FROM " . $GLOBALS['os']->table('goods_size') . " gs JOIN " . 
	        $GLOBALS['os']->table('size') . " s ON gs.size_id=s.size_id WHERE " . db_create_in(array_keys($goods_list), 'gs.goods_id');
	$s_res = $GLOBALS['db']->query($s_sql);
	while ($s_row = $GLOBALS['db']->fetchRow($s_res)){
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_id']   = $s_row['size_id'];
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_code'] = $s_row['size_code'];
	}
	
	$sql = "SELECT * FROM " . $GLOBALS['os']->table('barcode_generate_scheme') . " WHERE scheme_id=" . intval($scheme_id);
    $generate_scheme = $GLOBALS['db']->getRow($sql);
    
    foreach($goods_list as $goods_id=>$g){
    	if(!empty($goods_colors[$goods_id]) && !empty($goods_sizes[$goods_id])){
    		foreach ($goods_colors[$goods_id] as $gc){
    			foreach($goods_sizes[$goods_id] as $gs){ 
    				$barcode = barcode_generator($generate_scheme, $g['cat_code'], $g['goods_sn'], $gc['color_code'], $gs['size_code']);	
    				$is_only = $GLOBALS['db']->getOne("SELECT count(*) FROM " . $GLOBALS['os']->table('goods_barcode') . 
    				  							 " WHERE goods_id='$goods_id' AND color_id='$gc[color_id]' AND size_id='$gs[size_id]'");
    				if($is_only>0 && $is_cover==1){
    					$sql_ext = " ON DUPLICATE KEY UPDATE barcode='$barcode'";
    				}elseif($is_only>0 && $is_cover!=1){
    					continue;
    				}
    				$sql = "INSERT INTO " . $GLOBALS['os']->table('goods_barcode') . "(goods_id, cat_id, color_id, size_id," . 
    				       " barcode) VALUES ('$goods_id', '$g[cat_id]', '$gc[color_id]', '$gs[size_id]', '$barcode')" . $sql_ext;
    				$GLOBALS['db']->query($sql);
    			}
    		}
    	}
    }	
}

//function barcode_generator($scheme, $cat_code, $goods_code, $color_code, $size_code){
//	static  $refer_range           = array(1=>'类目', 2=>'商品', 3=>'颜色', 4=>'尺码');	
//    $barcode_haystack              = array();
//    $barcode                       = '';
//    
//    //array_shift($refer_range);
//	if(in_array($scheme['refer1'], array_keys($refer_range))){
//		array_push($barcode_haystack, get_module_code($scheme['refer1'], $cat_code, $goods_code, $color_code, $size_code));
//	}  
//	if(in_array($scheme['refer2'], array_keys($refer_range))){
//		array_push($barcode_haystack, get_module_code($scheme['refer2'], $cat_code, $goods_code, $color_code, $size_code));
//	}    
//	if(in_array($scheme['refer3'], array_keys($refer_range))){
//		array_push($barcode_haystack, get_module_code($scheme['refer3'], $cat_code, $goods_code, $color_code, $size_code));
//	}  
//	if(in_array($scheme['refer4'], array_keys($refer_range))){
//		array_push($barcode_haystack, get_module_code($scheme['refer4'], $cat_code, $goods_code, $color_code, $size_code));
//	}
//	$separate_sign = sprintf('%s', $scheme['separate_sign']);
//	$barcode4 = implode($separate_sign, $barcode_haystack);	
//	if($scheme['mode']==1){
//		$barcode_len4 = strlen($barcode4);
//		if($scheme['length'] > $barcode_len4){
//			$barcode4 .= generate_rand($scheme['length']-$barcode_len4);
//		}
//		return $barcode4;
//	}	
//    if($scheme['refer5']==1 && $scheme['refer5_rand_length']>0){
//
//		array_push($barcode_haystack, generate_rand(intval($scheme['refer5_rand_length'])));
//	}
//
//	$barcode = implode($separate_sign, $barcode_haystack);
//	return $barcode;
//}

//function get_module_code($refer, $cat_code, $goods_code, $color_code, $size_code){
//	static  $refer_range  = array(1=>'类目', 2=>'商品', 3=>'颜色', 4=>'尺码');	
//	//array_shift($refer_range);
//	if(!in_array($refer, array_keys($refer_range))){
//		return false;
//	}
//	switch ($refer){
//	    default:return false;exit();break;
//	    case 1:
//	    	$module_code = $cat_code;
//	    	break;
//	    case 2:
//	    	$module_code = $goods_code;
//	    	break;
//	    case 3:
//	    	$module_code = $color_code;
//	    	break;
//	    case 4:
//	    	$module_code = $size_code;
//	    	break;
//	}
//	return $module_code;
//}

function get_generate_scheme_list(){
	static  $refer_range  = array(1=>'类目', 2=>'商品', 3=>'颜色', 4=>'尺码');
	$scheme_list = array();
	
    $sql = "SELECT scheme_id, refer1, refer2, refer3, refer4, refer5 FROM " . 
    	   $GLOBALS['os']->table('barcode_generate_scheme') . " ORDER BY scheme_id DESC";
    $result = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($result)) {
    	$scheme_haystack = array();
    	if($row['refer1']>0 && in_array($row['refer1'], array_keys($refer_range))){
    		array_push($scheme_haystack, $refer_range[$row['refer1']]);
    	}
    	if($row['refer2']>0 && in_array($row['refer2'], array_keys($refer_range))){
    		array_push($scheme_haystack, $refer_range[$row['refer2']]);
    	}
     	if($row['refer3']>0 && in_array($row['refer3'], array_keys($refer_range))){
    		array_push($scheme_haystack, $refer_range[$row['refer3']]);
    	}
       	if($row['refer4']>0 && in_array($row['refer4'], array_keys($refer_range))){
    		array_push($scheme_haystack, $refer_range[$row['refer4']]);
    	}
    	if($row['refer5']>0){
    		array_push($scheme_haystack, '随机');
    	}
    	$scheme_list[$row['scheme_id']] = implode('+', $scheme_haystack);
    }

    return $scheme_list;	
}
?>